home *** CD-ROM | disk | FTP | other *** search
/ Celestin Apprentice 7 / Apprentice-Release7.iso / Source Code / C / Applications / Tcl-Tk 8.0 / Pre-installed version / tcl8.0 / library / http2.0 / http.tcl next >
Encoding:
Text File  |  1997-08-15  |  10.9 KB  |  461 lines  |  [TEXT/ALFA]

  1. # http.tcl --
  2. #
  3. #    Client-side HTTP for GET, POST, and HEAD commands.
  4. #    These routines can be used in untrusted code that uses 
  5. #    the Safesock security policy.  These procedures use a 
  6. #    callback interface to avoid using vwait, which is not 
  7. #    defined in the safe base.
  8. #
  9. # See the file "license.terms" for information on usage and
  10. # redistribution of this file, and for a DISCLAIMER OF ALL WARRANTIES.
  11. #
  12. # SCCS: @(#) http.tcl 1.6 97/08/07 16:48:32
  13.  
  14. package provide http 2.0    ;# This uses Tcl namespaces
  15.  
  16. namespace eval http {
  17.     variable http
  18.  
  19.     array set http {
  20.     -accept */*
  21.     -proxyhost {}
  22.     -proxyport {}
  23.     -useragent {Tcl http client package 2.0}
  24.     -proxyfilter http::ProxyRequired
  25.     }
  26.  
  27.     variable formMap
  28.     set alphanumeric    a-zA-Z0-9
  29.  
  30.     for {set i 1} {$i <= 256} {incr i} {
  31.     set c [format %c $i]
  32.     if {![string match \[$alphanumeric\] $c]} {
  33.         set formMap($c) %[format %.2x $i]
  34.     }
  35.     }
  36.     # These are handled specially
  37.     array set formMap {
  38.     " " +   \n %0d%0a
  39.     }
  40.  
  41.     namespace export geturl config reset wait formatQuery 
  42.     # Useful, but not exported: data size status code
  43. }
  44.  
  45. # http::config --
  46. #
  47. #    See documentaion for details.
  48. #
  49. # Arguments:
  50. #    args        Options parsed by the procedure.
  51. # Results:
  52. #        TODO
  53.  
  54. proc http::config {args} {
  55.     variable http
  56.     set options [lsort [array names http -*]]
  57.     set usage [join $options ", "]
  58.     if {[llength $args] == 0} {
  59.     set result {}
  60.     foreach name $options {
  61.         lappend result $name $http($name)
  62.     }
  63.     return $result
  64.     }
  65.     regsub -all -- - $options {} options
  66.     set pat ^-([join $options |])$
  67.     if {[llength $args] == 1} {
  68.     set flag [lindex $args 0]
  69.     if {[regexp -- $pat $flag]} {
  70.         return $http($flag)
  71.     } else {
  72.         return -code error "Unknown option $flag, must be: $usage"
  73.     }
  74.     } else {
  75.     foreach {flag value} $args {
  76.         if [regexp -- $pat $flag] {
  77.         set http($flag) $value
  78.         } else {
  79.         return -code error "Unknown option $flag, must be: $usage"
  80.         }
  81.     }
  82.     }
  83. }
  84.  
  85.  proc http::Finish { token {errormsg ""} } {
  86.     variable $token
  87.     upvar 0 $token state
  88.     global errorInfo errorCode
  89.     if {[string length $errormsg] != 0} {
  90.     set state(error) [list $errormsg $errorInfo $errorCode]
  91.     set state(status) error
  92.     }
  93.     catch {close $state(sock)}
  94.     catch {after cancel $state(after)}
  95.     if {[info exists state(-command)]} {
  96.     if {[catch {eval $state(-command) {$token}} err]} {
  97.         if {[string length $errormsg] == 0} {
  98.         set state(error) [list $err $errorInfo $errorCode]
  99.         set state(status) error
  100.         }
  101.     }
  102.     unset state(-command)
  103.     }
  104. }
  105.  
  106. # http::reset --
  107. #
  108. #    See documentaion for details.
  109. #
  110. # Arguments:
  111. #    token    Connection token.
  112. #    why    Status info.
  113. # Results:
  114. #        TODO
  115.  
  116. proc http::reset { token {why reset} } {
  117.     variable $token
  118.     upvar 0 $token state
  119.     set state(status) $why
  120.     catch {fileevent $state(sock) readable {}}
  121.     Finish $token
  122.     if {[info exists state(error)]} {
  123.     set errorlist $state(error)
  124.     unset state(error)
  125.     eval error $errorlist
  126.     }
  127. }
  128.  
  129. # http::geturl --
  130. #
  131. #    Establishes a connection to a remote url via http.
  132. #
  133. # Arguments:
  134. #        url        The http URL to goget.
  135. #        args        Option value pairs. Valid options include:
  136. #                -blocksize, -validate, -headers, -timeout
  137. # Results:
  138. #        Returns a token for this connection.
  139.  
  140.  
  141. proc http::geturl { url args } {
  142.     variable http
  143.     if ![info exists http(uid)] {
  144.     set http(uid) 0
  145.     }
  146.     set token [namespace current]::[incr http(uid)]
  147.     variable $token
  148.     upvar 0 $token state
  149.     reset $token
  150.     array set state {
  151.     -blocksize     8192
  152.     -validate     0
  153.     -headers     {}
  154.     -timeout     0
  155.     state        header
  156.     meta        {}
  157.     currentsize    0
  158.     totalsize    0
  159.         type            text/html
  160.         body            {}
  161.     status        ""
  162.     }
  163.     set options {-blocksize -channel -command -handler -headers \
  164.         -progress -query -validate -timeout}
  165.     set usage [join $options ", "]
  166.     regsub -all -- - $options {} options
  167.     set pat ^-([join $options |])$
  168.     foreach {flag value} $args {
  169.     if [regexp $pat $flag] {
  170.         # Validate numbers
  171.         if {[info exists state($flag)] && \
  172.             [regexp {^[0-9]+$} $state($flag)] && \
  173.             ![regexp {^[0-9]+$} $value]} {
  174.         return -code error "Bad value for $flag ($value), must be integer"
  175.         }
  176.         set state($flag) $value
  177.     } else {
  178.         return -code error "Unknown option $flag, can be: $usage"
  179.     }
  180.     }
  181.     if {! [regexp -nocase {^(http://)?([^/:]+)(:([0-9]+))?(/.*)?$} $url \
  182.         x proto host y port srvurl]} {
  183.     error "Unsupported URL: $url"
  184.     }
  185.     if {[string length $port] == 0} {
  186.     set port 80
  187.     }
  188.     if {[string length $srvurl] == 0} {
  189.     set srvurl /
  190.     }
  191.     if {[string length $proto] == 0} {
  192.     set url http://$url
  193.     }
  194.     set state(url) $url
  195.     if {![catch {$http(-proxyfilter) $host} proxy]} {
  196.     set phost [lindex $proxy 0]
  197.     set pport [lindex $proxy 1]
  198.     }
  199.     if {$state(-timeout) > 0} {
  200.     set state(after) [after $state(-timeout) [list http::reset $token timeout]]
  201.     }
  202.     if {[info exists phost] && [string length $phost]} {
  203.     set srvurl $url
  204.     set s [socket $phost $pport]
  205.     } else {
  206.     set s [socket $host $port]
  207.     }
  208.     set state(sock) $s
  209.  
  210.     # Send data in cr-lf format, but accept any line terminators
  211.  
  212.     fconfigure $s -translation {auto crlf} -buffersize $state(-blocksize)
  213.  
  214.     # The following is disallowed in safe interpreters, but the socket
  215.     # is already in non-blocking mode in that case.
  216.  
  217.     catch {fconfigure $s -blocking off}
  218.     set len 0
  219.     set how GET
  220.     if {[info exists state(-query)]} {
  221.     set len [string length $state(-query)]
  222.     if {$len > 0} {
  223.         set how POST
  224.     }
  225.     } elseif {$state(-validate)} {
  226.     set how HEAD
  227.     }
  228.     puts $s "$how $srvurl HTTP/1.0"
  229.     puts $s "Accept: $http(-accept)"
  230.     puts $s "Host: $host"
  231.     puts $s "User-Agent: $http(-useragent)"
  232.     foreach {key value} $state(-headers) {
  233.     regsub -all \[\n\r\]  $value {} value
  234.     set key [string trim $key]
  235.     if {[string length $key]} {
  236.         puts $s "$key: $value"
  237.     }
  238.     }
  239.     if {$len > 0} {
  240.     puts $s "Content-Length: $len"
  241.     puts $s "Content-Type: application/x-www-form-urlencoded"
  242.     puts $s ""
  243.     fconfigure $s -translation {auto binary}
  244.     puts $s $state(-query)
  245.     } else {
  246.     puts $s ""
  247.     }
  248.     flush $s
  249.     fileevent $s readable [list http::Event $token]
  250.     if {! [info exists state(-command)]} {
  251.     wait $token
  252.     }
  253.     return $token
  254. }
  255.  
  256. # Data access functions:
  257. # Data - the URL data
  258. # Status - the transaction status: ok, reset, eof, timeout
  259. # Code - the HTTP transaction code, e.g., 200
  260. # Size - the size of the URL data
  261.  
  262. proc http::data {token} {
  263.     variable $token
  264.     upvar 0 $token state
  265.     return $state(body)
  266. }
  267. proc http::status {token} {
  268.     variable $token
  269.     upvar 0 $token state
  270.     return $state(status)
  271. }
  272. proc http::code {token} {
  273.     variable $token
  274.     upvar 0 $token state
  275.     return $state(http)
  276. }
  277. proc http::size {token} {
  278.     variable $token
  279.     upvar 0 $token state
  280.     return $state(currentsize)
  281. }
  282.  
  283.  proc http::Event {token} {
  284.     variable $token
  285.     upvar 0 $token state
  286.     set s $state(sock)
  287.  
  288.     if [::eof $s] then {
  289.     Eof $token
  290.     return
  291.     }
  292.     if {$state(state) == "header"} {
  293.     set n [gets $s line]
  294.     if {$n == 0} {
  295.         set state(state) body
  296.         if ![regexp -nocase ^text $state(type)] {
  297.         # Turn off conversions for non-text data
  298.         fconfigure $s -translation binary
  299.         if {[info exists state(-channel)]} {
  300.             fconfigure $state(-channel) -translation binary
  301.         }
  302.         }
  303.         if {[info exists state(-channel)] &&
  304.             ![info exists state(-handler)]} {
  305.         # Initiate a sequence of background fcopies
  306.         fileevent $s readable {}
  307.         CopyStart $s $token
  308.         }
  309.     } elseif {$n > 0} {
  310.         if [regexp -nocase {^content-type:(.+)$} $line x type] {
  311.         set state(type) [string trim $type]
  312.         }
  313.         if [regexp -nocase {^content-length:(.+)$} $line x length] {
  314.         set state(totalsize) [string trim $length]
  315.         }
  316.         if [regexp -nocase {^([^:]+):(.+)$} $line x key value] {
  317.         lappend state(meta) $key $value
  318.         } elseif {[regexp ^HTTP $line]} {
  319.         set state(http) $line
  320.         }
  321.     }
  322.     } else {
  323.     if [catch {
  324.         if {[info exists state(-handler)]} {
  325.         set n [eval $state(-handler) {$s $token}]
  326.         } else {
  327.         set block [read $s $state(-blocksize)]
  328.         set n [string length $block]
  329.         if {$n >= 0} {
  330.             append state(body) $block
  331.         }
  332.         }
  333.         if {$n >= 0} {
  334.         incr state(currentsize) $n
  335.         }
  336.     } err] {
  337.         Finish $token $err
  338.     } else {
  339.         if [info exists state(-progress)] {
  340.         eval $state(-progress) {$token $state(totalsize) $state(currentsize)}
  341.         }
  342.     }
  343.     }
  344. }
  345.  proc http::CopyStart {s token} {
  346.     variable $token
  347.     upvar 0 $token state
  348.     if [catch {
  349.     fcopy $s $state(-channel) -size $state(-blocksize) -command \
  350.         [list http::CopyDone $token]
  351.     } err] {
  352.     Finish $token $err
  353.     }
  354. }
  355.  proc http::CopyDone {token count} {
  356.     variable $token
  357.     upvar 0 $token state
  358.     set s $state(sock)
  359.     incr state(currentsize) $count
  360.     if [info exists state(-progress)] {
  361.     eval $state(-progress) {$token $state(totalsize) $state(currentsize)}
  362.     }
  363.     if [::eof $s] {
  364.     Eof $token
  365.     } else {
  366.     CopyStart $s $token
  367.     }
  368. }
  369.  proc http::Eof {token} {
  370.     variable $token
  371.     upvar 0 $token state
  372.     if {$state(state) == "header"} {
  373.     # Premature eof
  374.     set state(status) eof
  375.     } else {
  376.     set state(status) ok
  377.     }
  378.     set state(state) eof
  379.     Finish $token
  380. }
  381.  
  382. # http::wait --
  383. #
  384. #    See documentaion for details.
  385. #
  386. # Arguments:
  387. #    token    Connection token.
  388. # Results:
  389. #        The status after the wait.
  390.  
  391. proc http::wait {token} {
  392.     variable $token
  393.     upvar 0 $token state
  394.  
  395.     if {![info exists state(status)] || [string length $state(status)] == 0} {
  396.     vwait $token\(status)
  397.     }
  398.     if {[info exists state(error)]} {
  399.     set errorlist $state(error)
  400.     unset state(error)
  401.     eval error $errorlist
  402.     }
  403.     return $state(status)
  404. }
  405.  
  406. # http::formatQuery --
  407. #
  408. #    See documentaion for details.
  409. #    Call http::formatQuery with an even number of arguments, where 
  410. #    the first is a name, the second is a value, the third is another 
  411. #    name, and so on.
  412. #
  413. # Arguments:
  414. #    args    A list of name-value pairs.
  415. # Results:
  416. #        TODO
  417.  
  418. proc http::formatQuery {args} {
  419.     set result ""
  420.     set sep ""
  421.     foreach i $args {
  422.     append result  $sep [mapReply $i]
  423.     if {$sep != "="} {
  424.         set sep =
  425.     } else {
  426.         set sep &
  427.     }
  428.     }
  429.     return $result
  430. }
  431.  
  432. # do x-www-urlencoded character mapping
  433. # The spec says: "non-alphanumeric characters are replaced by '%HH'"
  434. # 1 leave alphanumerics characters alone
  435. # 2 Convert every other character to an array lookup
  436. # 3 Escape constructs that are "special" to the tcl parser
  437. # 4 "subst" the result, doing all the array substitutions
  438.  
  439.  proc http::mapReply {string} {
  440.     variable formMap
  441.     set alphanumeric    a-zA-Z0-9
  442.     regsub -all \[^$alphanumeric\] $string {$formMap(&)} string
  443.     regsub -all \n $string {\\n} string
  444.     regsub -all \t $string {\\t} string
  445.     regsub -all {[][{})\\]\)} $string {\\&} string
  446.     return [subst $string]
  447. }
  448.  
  449. # Default proxy filter. 
  450.  proc http::ProxyRequired {host} {
  451.     variable http
  452.     if {[info exists http(-proxyhost)] && [string length $http(-proxyhost)]} {
  453.     if {![info exists http(-proxyport)] || ![string length $http(-proxyport)]} {
  454.         set http(-proxyport) 8080
  455.     }
  456.     return [list $http(-proxyhost) $http(-proxyport)]
  457.     } else {
  458.     return {}
  459.     }
  460. }
  461.